/**
 * HP Subscriber, Network, and Application Policy
 *
 * Copyright (C) 2009-2014 Hewlett-Packard Company
 */
package com.hp.snap.gr.action.impl;

import com.hp.snap.gr.action.ActionHandler;
import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.jaxb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>ActionHandlerFactory</p>
 *
 * @author Joey Yi
 */
public class ActionHandlerFactory {
    private static Logger logger = LoggerFactory.getLogger(ActionHandlerFactory.class);

    private static Map<String, ActionHandler> ACTION_HANDLERS = new HashMap<String, ActionHandler>();

    static {
        ACTION_HANDLERS.put(LocalShellActionType.class.getName(), new LocalShellActionHandler());
        ACTION_HANDLERS.put(RemoteShellActionType.class.getName(), new RemoteShellActionHandler());
        ACTION_HANDLERS.put(FileReplaceActionType.class.getName(), new FileReplaceActionHandler());
        ACTION_HANDLERS.put(SCPFromRemoteActionType.class.getName(), new SCPFromRemoteActionHandler());
        ACTION_HANDLERS.put(SCPToRemoteActionType.class.getName(), new SCPToRemoteActionHandler());
        ACTION_HANDLERS.put(SNMPTrapActionType.class.getName(), new SNMPTrapActionHandler());
        ACTION_HANDLERS.put(ExportVoltDBConfigurationActionType.class.getName(), new ExportVoltDBConfigurationActionHandler());
        ACTION_HANDLERS.put(ExportMySqlDBActionType.class.getName(), new ExportMySqlDBActionHandler());
        ACTION_HANDLERS.put(ImportVoltDBConfigurationActionType.class.getName(), new ImportVoltDBConfigurationActionHandler());
    }

    public static ActionHandler getActionHandler(ActionType action) throws ActionException {
        ActionHandler handler;

        if (action instanceof GeneralActionType) {
            String actionHandlerClass = ((GeneralActionType) action).getActionHandler().getHandler();

            if (logger.isTraceEnabled()) {
                logger.trace("The action handler class name is: {} ", actionHandlerClass);
            }

            try {
                handler = (ActionHandler) Class.forName(actionHandlerClass).newInstance();
            } catch (Exception e) {
                throw new ActionException("Cannot create action handler instance for GeneralAction: " + action.getName(), e);

            }
            return handler;
        }

        handler = ACTION_HANDLERS.get(action.getClass().getName());

        if (handler == null) {
            throw new ActionException("Action handler not exists for type: " + action.getClass().getName());
        }
        return handler;
    }
}
